<!-- 商家入驻界面 -->
<template>
  <up-subsection :list="list" mode="subsection" :current="0" @change="sectionChange"></up-subsection>
  <view class="content">
    <view class="main" v-show="curNow == 0">
      <uni-forms ref="formRef" :model="user" labelWidth="80px">
        <uni-forms-item label="店铺头像" name="avatar">
          <view class="avatar">
            <img @click="selectAvatar(-1)" :src="avatarUrl" alt="">
          </view>
        </uni-forms-item>
        <uni-forms-item label="店铺名称" name="storeName" required>
          <uni-easyinput v-model="user.storeName" placeholder="请输入店铺名称(样式: x食堂x楼xxx店铺)" />
        </uni-forms-item>
        <uni-forms-item label="联系电话" name="phonenumber" required>
          <uni-easyinput v-model="user.phonenumber" placeholder="请输入手机号码" />
        </uni-forms-item>
        <uni-forms-item label="店铺类型" name="kinds" required>
          <uni-data-checkbox v-model="user.kinds" :localdata="kinds" />
        </uni-forms-item>
        <uni-forms-item label="店铺位置" name="address" required @click="selectAddress">
          <view class="address">{{ address.join("-") || '请选择店铺地址' }}</view>
        </uni-forms-item>
      </uni-forms>
      <view class="materials">
        <view class="m_top">上传相关材料</view>
        <view class="m_main">
          <view class="m_item" v-for="(item, index) in 3" :key="item">
            <view class="avatar" @click="selectAvatar(index)">
              <img v-if="[businessLicense, identityFront, identityReverse][index]"
                :src="[businessLicense, identityFront, identityReverse][index]" alt="">
            </view>
            <view class="m_text">{{ ['营业执照', "法人身份证(正面)", "法人身份证(反面)"][index] }}</view>
          </view>
        </view>
      </view>
      <button type="primary" @click="submit">提交</button>
    </view>
    <view class="aduit_list" v-if="curNow == 1">
      <view class="audit_item" v-for="item in selfAudits" :key="item._id">
        <view class="a_top">
          <view class="a_t_left">店名: {{ item.storeName }}</view>
          <view class="a_t_right">商家名称: {{ item.sellerName }}</view>
        </view>
        <view class="a_center">
          <view class="c_top">店铺位置: {{ `${item.canteenName}` + `-窗口${item.window}` }}</view>
          <view class="c_bottom">联系电话: {{ item.phonenumber }}</view>
        </view>
        <view class="a_bottom">
          <view class="b_left">申请时间: {{ formatterTime(item.startTime) || '' }}</view>
          <view :class="{ b_right: true, wait: item.isPass == '1', fail: item.isPass == '-1', }">{{
    getAduitStatus(item.isPass) }}</view>
        </view>
        <view class="noPass" v-if="item.isPass == '-1' && item.failReason">未通过原因: {{ item.failReason }}</view>
      </view>
    </view>
    <!-- 地址选择 -->
    <up-picker :show="showAddress" ref="uPickerRef" :columns="columns" @confirm="confirm1" @cancel="cancel1"
      @change="changeHandler" closeOnClickOverlay @close="close1"></up-picker>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { getUserProfile } from "@/api/system/user";
import useUserStore from '@/store/modules/user'
import { getUserInfo } from "@/api/user/index";
import { addAudit, getSelfAudit } from "@/api/audit/index";
import { getAllSchoolInfo } from "@/api/school/index";

import config from '@/config'

const baseUrl = config.baseUrl

// 生命周期钩子
onMounted(async () => {
  // await getUser();
  await loadDefaultAvatar();
  formRef.value.setRules(rules);
});

// 顶部 tab栏 
const list = ref([
  { name: '入驻申请' },
  { name: '审核记录' },
]);

// 当前 tab下标
const curNow = ref(0);
function sectionChange(index) {
  curNow.value = index;
  console.log('curNow.value: ', curNow.value);
}

const userStore = useUserStore()
// 创建响应式数据
const formRef = ref(null);
const user = reactive({
  storeName: "",
  phonenumber: "",
  kinds: ""
});
const kinds = [
  {
    text: '面食',
    value: "0"
  },
  {
    text: '套餐饭',
    value: "1"
  },
  {
    text: '小吃',
    value: "2"
  },
  {
    text: '饮品',
    value: "3"
  },
  {
    text: '水果',
    value: "4"
  },
  {
    text: '其他',
    value: "-1"
  }
];
const rules = {
  storeName: {
    rules: [
      {
        required: true,
        errorMessage: '店铺名称不能为空'
      }
    ]
  },
  phonenumber: {
    rules: [
      {
        required: true,
        errorMessage: '联系电话不能为空'
      },
      {
        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
        errorMessage: '请输入正确的手机号码'
      }
    ]
  },
  kinds: {
    rules: [
      {
        required: true,
        errorMessage: '店铺类型不能为空'
      }
    ]
  },
};

/**
 * 动态导入默认头像
 */
const loadDefaultAvatar = async () => {
  // if (!userStore.userInfo.avatar) {
  try {
    const module = await import('@/assets/mine/defautAvatar.svg');
    avatarUrl.value = module.default;
  } catch (error) {
    console.error('Failed to load image:', error);
  }
  // } else {
  //   avatarUrl.value = userStore.userInfo.avatar;
  // }
};

/**
 * 店铺地址选择
 */
const showAddress = ref(false);
let address = ref([])

// 查询所有学校数据
getAllSchoolInfo().then(res => {
  if (res.code == 200) {
    let nowSchool = res.schoolData.find(item => item._id == userStore.userInfo.schoolId)
    if (nowSchool) {
      // 获取食堂名称列表
      const canteenNames = nowSchool.canteen.map(item => item.name)
      columns[0] = canteenNames

      // 根据每个食堂的窗口数生成对应的窗口选项
      columnData.length = 0 // 清空原有数据
      nowSchool.canteen.forEach(item => {
        const windowCount = parseInt(item.windowNum)
        const windows = Array.from({ length: windowCount }, (_, i) => `窗口${i + 1}`)
        columnData.push(windows)
      })

      // 设置默认第一个食堂的窗口选项
      columns[1] = columnData[0]
    }
  }
})

const columns = reactive([[], []]); // 初始化为空数组
const columnData = reactive([]); // 初始化为空数组
const uPickerRef = ref(null)
const changeHandler = (e) => {
  const {
    columnIndex,
    value,
    values,
    index,
  } = e;

  if (columnIndex === 0) {
    uPickerRef.value.setColumnValues(1, columnData[index]);
  }
};

function selectAddress() {
  showAddress.value = true
}

const confirm1 = (e) => {
  console.log('confirm', e);
  address.value = e.value
  console.log(' address.value: ', address.value);
  showAddress.value = false;
};
const cancel1 = () => {
  showAddress.value = false;
};
const close1 = () => {
  showAddress.value = false;
};


/**
 * 提交表单
 */
const submit = async () => {
  if (userStore.userInfo.user_level == 1) {
    uni.showToast({ title: "您已经是商家了, 请勿重复提交~", icon: "error" })
    return
  }

  try {
    if (avatarUrl.value == "/src/assets/mine/defautAvatar.svg") {
      uni.showToast({ title: "请选择店铺头像", icon: "error" })
      return
    }

    // 表单数据要正确
    await formRef.value.validate();

    if (!userStore.userId) {
      uni.showToast({ title: "请先登录", icon: "error" })
      return
    } else if (!userStore.userInfo.username) {
      uni.showToast({ title: "网络异常, 请稍后再试", icon: "error" })
      return
    } else if (address.value.length == 0) {
      uni.showToast({ title: "请选择店铺位置", icon: "error" })
      return
    }

    // 对应的材料图片全部选择
    if (!businessLicense.value) {
      uni.showToast({ title: "请选择营业执照", icon: "error" })
      return
    } else if (!identityFront.value) {
      uni.showToast({ title: "请选择身份证正面", icon: "error" })
      return
    } else if (!identityReverse.value) {
      uni.showToast({ title: "请选择身份证反面", icon: "error" })
      return
    }

    let params = {}
    params = {
      sellerId: userStore.userId,
      sellerName: userStore.userInfo.username,
      schoolId: userStore.userInfo.schoolId,
      ...user,
      canteenName: address.value[0],
      window: address.value[1][address.value[1].length - 1]
    }
    console.log('params: ', params);
    addAudit(params).then(res => {
      if (res.code == 200) {
        uploadAvatar(res.data._id)
      } else if (res.code == 202) {
        uni.showToast({ title: res.message, icon: "error" })
      } else if (res.code == 203) {
        uni.showToast({ title: res.message, icon: "error" })
      }
      else {
        uni.showToast({
          title: '网络开了点小差, 请稍后再试~',
          mask: false,
          duration: 1000
        });
      }
    }).catch(err => {
      uni.showToast({
        title: '网络开了点小差, 请稍后再试~',
        mask: false,
        duration: 1000
      });
    })
  } catch (error) {
    console.error('Form validation failed:', error);
  }
};

// 选择头像处理函数
const selectAvatar = (type) => {
  console.log(type);
  uni.chooseImage({
    count: 1, // 限制选择一张图片
    sizeType: ["original", "compressed"], // 可以选择原图或压缩图
    sourceType: ["album", "camera"], // 从相册或相机选择
    success: async (res) => {
      const tempFilePath = res.tempFilePaths[0]; // 获取选择的图片临时路径
      if (type == -1) {
        avatarUrl.value = tempFilePath
      } else if (type == 0) {
        businessLicense.value = tempFilePath
      } else if (type == 1) {
        identityFront.value = tempFilePath
      } else if (type == 2) {
        identityReverse.value = tempFilePath
      }
    },
    fail: (err) => {
      console.error("选择头像失败：", err);
    }
  });
};

const avatarUrl = ref(''); // 店铺头像
const businessLicense = ref(''); // 营业执照
const identityFront = ref(''); // 身份证正面
const identityReverse = ref(''); // 身份证反面

// 上传头像的方法
const uploadAvatar = (auditId) => {
  const files = [
    { name: 'storeIcon', filePath: avatarUrl.value },
    { name: 'businessLicense', filePath: businessLicense.value },
    { name: 'identityFront', filePath: identityFront.value },
    { name: 'identityReverse', filePath: identityReverse.value },
  ];
  let flag = true
  files.forEach(item => {
    uni.uploadFile({
      url: baseUrl + '/audit/upload/auditImage',
      filePath: item.filePath,
      formData: {
        userId: userStore.userId,
        auditId: auditId,
        key: item.name
      },
      success: (uploadRes) => {
        // console.log('uploadRes: ', uploadRes);
        const res = JSON.parse(uploadRes.data); // 解析返回的数据
        if (res.code == '200') {
          console.log('头像上传成功,URL:', res.path);
        } else {
          console.error('头像上传失败：', res.message);
          flag = false
        }
      },
      fail: (err) => {
        console.error('头像上传失败：', err);
        flag = false
      },
    });
  })

  if (flag) {
    uni.showToast({
      title: '提交成功, 请耐心等待审核~',
      mask: false,
      duration: 1000
    });
    setTimeout(() => {
      uni.reLaunch({
        url: '/pages_mine/pages/addStore/index' // 替换为当前页面的路径
      });
    }, 1000);
  }
};

/**
 * 获取当前用户的审核记录
 */
let selfAudits = ref([])
getSelfAudit({ userId: userStore.userId }).then(res => {
  if (res.code == 200) {
    selfAudits.value = res.data
    console.log('selfAudits.value: ', selfAudits.value);
  }
})

// 时间格式化
function formatterTime(time) {
  if (!time) {
    return ''
  }

  const date = new Date(Number(time));

  // 获取年、月、日、时、分、秒
  const year = date.getFullYear(); // 年份
  const month = date.getMonth() + 1; // 月份（0-11，需要加1）
  const day = date.getDate(); // 日期
  const hours = date.getHours(); // 小时
  const minutes = date.getMinutes(); // 分钟
  const seconds = date.getSeconds(); // 秒

  // 返回格式化后的字符串
  return `${year}年/${month}月/${day}日/${hours}时/${minutes}分/${seconds}秒`;
}

/**
 * 获取审核状态
 */
function getAduitStatus(status) {
  if (status == '0') {
    return '待审核'
  } else if (status == '1') {
    return '审核成功'
  } else if (status == '-1') {
    return '审核失败'
  }
}

</script>

<style lang="scss">
.content {
  height: calc(100vh - var(--window-top) - 100rpx);
  display: flex;
  flex-direction: column;
  position: relative;
  background-color: $uni-bg-color-grey;
  overflow: auto;
  background-color: #ffffff;

  .main,
  .aduit_list {
    overflow: auto;
    padding: 30rpx;
  }
}

page {
  background-color: #ffffff;
}

.example {
  padding: 30rpx;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 30rpx;
}

.button-group {
  margin-top: 40rpx;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.uni-forms-item {
  margin-bottom: 30rpx;
}

.button {
  display: flex;
  align-items: center;
  height: 70rpx;
  line-height: 70rpx;
  margin-left: 20rpx;
}

.avatar {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx solid #edf2fa;
  border-radius: 50%;

  img {
    width: 100%;
    height: 100%;
    border-radius: 50%;
  }
}

.address {
  height: 100%;
  display: flex;
  align-items: center;
  color: $uni-text-color-grey
}

.materials {
  display: flex;
  width: 100%;
  flex-direction: column;
  border: 1rpx solid $uni-border-color;
  margin-bottom: 20rpx;

  .m_top {
    width: 100%;
    height: 80rpx;
    display: flex;
    align-items: center;
  }

  .m_main {
    width: 100%;
    display: flex;
    padding: 20rpx;
    background-color: #fafafa;
    justify-content: space-between;

    .m_item {
      display: flex;
      flex-direction: column;
      align-items: center;

      .avatar {
        width: 200rpx;
        height: 200rpx;
        border: 1rpx solid $uni-border-color;
        border-radius: 0;
        background-image: url("@/assets/mine/addStore/add.svg");
        background-size: 30%;
        background-repeat: no-repeat;
        background-position: center;

        img {
          width: 100%;
          height: 100%;
          border-radius: 0;
        }
      }

      .m_text {
        margin-top: 20rpx;
        color: $uni-text-color;
        font-size: 24rpx;
      }
    }
  }
}

.aduit_list {
  padding: 30rpx;
  display: flex;
  flex-direction: column;

  .audit_item {
    width: 100%;
    border: 1rpx solid $uni-border-color;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .a_top {
      display: flex;
      width: 100%;
      align-items: center;
      justify-content: space-between;
      color: $uni-text-color;
      font-size: 28rpx;

      .a_t_right {
        font-size: 24rpx;
        padding: 8rpx 24rpx;
        border: 1rpx solid $uni-border-color;
      }
    }

    .a_center {
      width: 100%;
      display: flex;
      flex-direction: column;
      margin: 20rpx 0;
      font-size: 28rpx;
      color: $uni-text-color ;

      .c_bottom {
        margin-top: 16rpx;
      }
    }

    .a_bottom {
      width: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .b_left {
        color: $uni-text-color-grey;
        font-size: 24rpx;
      }

      .b_right {
        color: $uni-color-warning;
        font-size: 28rpx;
      }

      .wait {
        color: $uni-color-success ;
      }

      .fail {
        color: $uni-text-color-red;
      }

    }

  }

  .noPass {
    color: $uni-color-error;
    font-size: 20rpx;
    margin-top: 10rpx;
  }
}
</style>